﻿
module Sustainalytics.Accounts.Admin {
    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;
    export class IpAuthenticationService {
        constructor(
           private $q: ng.IQService,
            private $http: ng.IHttpService,
            private $location: ng.ILocationService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjectsAdmin: CommonAdmin.IStaticObjects
            ) {
        }

        private accountsUrl(): string {
            var ctx = this;
            return ctx.$location.protocol() + "://" + ctx.$location.host() + ":" + ctx.$location.port() + "/accountsserv/api/v1/accounts/";
        }

        public getAccountIpData(id: string): ng.IPromise<AccountIpAuthenticationDto> {
            var ctx = this;

            var def = this.$q.defer();

            var promise = this.$http.get(ctx.accountsUrl() + "ipauthentication/" + id, {});
            promise
                .success(data=> { def.resolve(data); })
                .error(err => {
                ctx.showError(err);
                def.reject();
                });

            return def.promise;
        }

        public putAccountIpData(data: AccountIpAuthenticationDto):ng.IPromise<any> {
            var ctx = this;

            var def = this.$q.defer();
            var nameAccount = data.accountName;
            var url = ctx.accountsUrl() + "ipauthentication";
            console.log(url);
            var promise = this.$http.post(url, data);
            promise
                .success(data => {
                def.resolve(data);
                    ctx.notificationFactory.success("The update operation for the account "+nameAccount+" was succesful");
                })
                .error(err => {
                ctx.showError(err);
                def.reject();
            });

            return def.promise;
        }

        private showError(err) {
            var ctx = this;
            console.log(err);
            if (err && err['code']) {
                ctx.notificationFactory.error('', ctx.staticObjectsAdmin.getMessageByInternalCode(err['code']));
                return;
            }
            if (err) {
                ctx.notificationFactory.error("It was an exception on server side", err);
            }
        }
    }

    var mod = angular.module(accountAdminModuleName);

    mod.service('IpAuthenticationService',
        ['$q', '$http', '$location','notificationFactory', 'staticObjectsAdmin', IpAuthenticationService]);
}